"""
需求管理API路由
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime

from ...core.database import get_db
from ...core.security import get_current_user
from ...models.user import User
from ...models.requirement import Requirement
from ...schemas.requirement import RequirementCreate, RequirementUpdate, RequirementResponse
from ...services.requirement_service import RequirementService

router = APIRouter()
requirement_service = RequirementService()


@router.get("/", response_model=List[RequirementResponse])
async def get_requirements(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    search: Optional[str] = None,
    tag_filter: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取需求列表"""
    try:
        requirements = requirement_service.get_requirements(
            db=db,
            page=page,
            page_size=page_size,
            search=search,
            tag_filter=tag_filter,
            created_by=current_user.id
        )
        return requirements
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取需求列表失败: {str(e)}")


@router.post("/", response_model=RequirementResponse)
async def create_requirement(
    requirement: RequirementCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建需求"""
    try:
        return requirement_service.create_requirement(
            db=db,
            requirement=requirement,
            created_by=current_user.id
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建需求失败: {str(e)}")


@router.get("/{requirement_id}", response_model=RequirementResponse)
async def get_requirement_detail(
    requirement_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取需求详情"""
    try:
        requirement = requirement_service.get_requirement_by_id(
            db=db,
            requirement_id=requirement_id,
            user_id=current_user.id
        )
        if not requirement:
            raise HTTPException(status_code=404, detail="需求不存在")
        return requirement
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取需求详情失败: {str(e)}")


@router.put("/{requirement_id}", response_model=RequirementResponse)
async def update_requirement(
    requirement_id: int,
    requirement: RequirementUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新需求"""
    try:
        updated_requirement = requirement_service.update_requirement(
            db=db,
            requirement_id=requirement_id,
            requirement=requirement,
            user_id=current_user.id
        )
        if not updated_requirement:
            raise HTTPException(status_code=404, detail="需求不存在")
        return updated_requirement
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新需求失败: {str(e)}")


@router.delete("/{requirement_id}")
async def delete_requirement(
    requirement_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除需求"""
    try:
        success = requirement_service.delete_requirement(
            db=db,
            requirement_id=requirement_id,
            user_id=current_user.id
        )
        if not success:
            raise HTTPException(status_code=404, detail="需求不存在")
        return {"message": "需求删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除需求失败: {str(e)}") 